package com.tbit.uqbike.webmanager.business.userfacelog.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.User;
import com.tbit.uqbike.object.pojo.vo.UserFaceDataVO;
import com.tbit.common.entity.view.PageResult;
import com.tbit.uqbike.service.business.UserFaceDataService;
import com.tbit.uqbike.service.business.UserService;
import com.tbit.uqbike.webmanager.business.userfacelog.dao.log.UserFaceLogDao;
import com.tbit.uqbike.webmanager.business.userfacelog.object.UserFaceLog;
import com.tbit.uqbike.webmanager.business.userfacelog.object.vo.UserFaceLogVo;
import com.tbit.uqbike.webmanager.dao.core.UserDao;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author <a href="mailto:zheng.zebiao@tbit.com.cn">zb</a>
 * @since 2024/9/3
 */
@Service
@RequiredArgsConstructor
public class UserFaceLogService extends ServiceImpl<UserFaceLogDao, UserFaceLog> {
    final UserService userService;
    final UserFaceDataService userFaceDataService;
    final UserDao userDao;

    public PageResult<UserFaceLogVo> getRecordList(Integer page, Integer size, Integer accountId, String name, String phone, String idNO, Boolean success) {
        // 查询条件对应的用户
        List<Integer> userIds = null;
        if (name != null || phone != null || idNO != null) {
            List<User> users = userService.getIdByAccountIdAndPhoneAndNameAndIdNo(accountId, phone, name, idNO);
            if (users.isEmpty()) {
                return PageResult.convertPage(PageInfo.emptyPageInfo());
            }

            userIds = users.stream()
                    .map(User::getUserId)
                    .collect(Collectors.toList());
        }

        // 查询人脸识别记录
        QueryWrapper<UserFaceLog> queryWrapper = Wrappers.<UserFaceLog>query()
                .eq("accountId", accountId)
                .in(CollUtil.isNotEmpty(userIds), "userId", userIds)
                .orderByDesc("addTime");
        if (success != null) {
            if (success) {
                queryWrapper.eq("success", 1);
            } else {
                queryWrapper.ne("success", 1); // 该字段可能为3，表示识别成功但不是同一个人
            }
        }
        Page<UserFaceLog> pageInfo = this.page(Page.of(page, size), queryWrapper);
        if (pageInfo.getRecords().isEmpty()) {
            return PageResult.convertPage(PageInfo.emptyPageInfo());
        }

        // 查询人脸缓存数据
        List<Integer> finalUserIds = pageInfo.getRecords().stream()
                .map(UserFaceLog::getUserId)
                .distinct()
                .collect(Collectors.toList());
        List<UserFaceDataVO> faceDataList = userFaceDataService.list(Wrappers.<UserFaceDataVO>query()
                .in("userId", finalUserIds)
                .eq("accountId", accountId)
        );
        Map<Integer, UserFaceDataVO> faceDataMap = faceDataList.stream()
                .collect(Collectors.toMap(UserFaceDataVO::getUserId, Function.identity()));

        // 查询用户数据
        Map<Integer, User> userMap = userDao.getByUserIds(MapUtil.of("userIds", finalUserIds)).stream()
                .collect(Collectors.toMap(User::getUserId, Function.identity()));

        List<UserFaceLogVo> list = pageInfo.getRecords().stream()
                .map(u -> {
                    UserFaceLogVo vo = new UserFaceLogVo();
                    BeanUtil.copyProperties(u, vo);
                    User user = userMap.get(u.getUserId());
                    vo.setName(user.getName());
                    vo.setPhone(user.getPhone());
                    vo.setIdNO(user.getIdNO());
                    if (faceDataMap.containsKey(u.getUserId())) {
                        vo.setCacheUrl(faceDataMap.get(u.getUserId()).getUrl());
                    }
                    return vo;
                })
                .collect(Collectors.toList());
        PageResult<UserFaceLogVo> result = new PageResult<>();
        result.setList(list);
        result.setPage((int) pageInfo.getCurrent());
        result.setSize((int) pageInfo.getSize());
        result.setTotal(pageInfo.getTotal());
        result.setTotalPages((int) pageInfo.getPages());
        return result;
    }

    /**
     * 获取人脸识别记录详情
     * @param faceId 人脸识别记录ID
     * @return
     */
    public UserFaceLogVo getDetail(Integer faceId) {
        UserFaceLog userFaceLog = this.getById(faceId);
        if (Objects.isNull(userFaceLog)){
            return null;
        }
        User user = userService.getByUserId(userFaceLog.getUserId());
        if (Objects.isNull(user)){
            throw new BaseException("用户不存在");
        }

        /*查询人脸识别缓存*/
        UserFaceDataVO faceData = userFaceDataService.lambdaQuery()
                .eq(UserFaceDataVO::getUserId, userFaceLog.getUserId())
                .eq(UserFaceDataVO::getAccountId, userFaceLog.getAccountId())
                .one();

        UserFaceLogVo userFaceLogVo = new UserFaceLogVo();
        BeanUtil.copyProperties(userFaceLog, userFaceLogVo);
        userFaceLogVo.setName(user.getName())
                .setPhone(user.getPhone())
                .setIdNO(user.getIdNO())
                .setCacheUrl(Objects.nonNull(faceData) ? faceData.getUrl() : null);
        return userFaceLogVo;
    }
}
